<?php
/**
 * Created by JiangJiaCai.
 * User: Administrator
 * Date: 2017/7/7 0007
 * Time: 16:39
 */

namespace ext\lib;


use ext\fun\EntityFun;

class BaseDaoImpl
{
    const DEFAULT_PRI_KEY = 'id';
    public final function createData(string $entityName , SimpleRpc $rpc){
        try{
            $entity = EntityFun::rpcPushEntity($entityName , $rpc);
            $entity->save();
            return $entity;
        }catch (\Exception $e){
            logger()->error('create error' . $e->getMessage());
        }
        return false;
    }

    public final function updateData(string $entityName , SimpleRpc $rpc , string $pri_key = 'id'){
        try{
            $entityName::findOrFail($rpc->$pri_key)->update($rpc->toArray());
            return true;
        }catch (\Exception $e){
            logger()->error('update error' . $e->getMessage());
        }
        return false;
    }

    public final function getOne(string $entityName , int $id , string $pri_key = 'id'){
        if ( !$this->isUseIdPriKey($pri_key)){
            return $entityName::where([
                $pri_key => $id
            ])->first();
        }else{
            return $entityName::find($id);
        }
    }

    public final function delete(string $entityName , int $id , string $pri_key = 'id'){
        try{
            if ( !$this->isUseIdPriKey($pri_key)){
                $entityName::where([
                    $pri_key => $id
                ])->first()->delete();
            }else{
                $entityName::find($id)->delete();
            }
            return true;
        }catch (\Exception $e){
            logger()->error('delete error' . $e->getMessage());
            return false;
        }
    }

    public final function getAllList(string $entityName){
        return $entityName::all();
    }

    public final function getList(string $entityName , int $limit , array $where = [] , string $order = 'created_at' , string $sort = 'desc'){
        return $entityName::where($where)
            ->orderBy($order,$sort)
            ->limit($limit)->get();
    }

    public function getPageList(string $entityName ,int $pageSize ,  array $where = [] , string $order='created_at' , string $sort = 'desc'){
        return $entityName::where($where)
            ->orderBy($order , $sort)
            ->paginate($pageSize);
    }
    protected function isUseIdPriKey($pri_key){
        return $pri_key == self::DEFAULT_PRI_KEY;
    }
}